<template>
  <div class="purchase-order-detail">
    <van-loading v-if="loading" size="24px">加载中...</van-loading>
    
    <template v-else>
      <van-form @submit="saveChanges">
        <van-cell-group>
          <!-- 可编辑字段 -->
          <van-field
            v-model="editableOrder.name"
            label="供应商名称"
            placeholder="请输入供应商名称"
            :readonly="!isEditing"
          />
          <van-field
            v-model="editableOrder.orderDate"
            label="订单日期"
            placeholder="请选择订单日期"
            :readonly="!isEditing"
            @click="isEditing && (showDatePicker = true)"
          />
          <van-field
            v-model="editableOrder.totalAmount"
            label="总金额"
            placeholder="请输入总金额"
            type="number"
            :readonly="!isEditing"
          />
          
          <!-- 状态显示 -->
          <van-cell title="状态">
            <van-tag :type="statusTagType">{{ order.status }}</van-tag>
          </van-cell>
          
          <!-- 只读信息 -->
          <van-cell title="订单ID" :value="order.purchaseOrderId" />
          <van-cell title="创建人" :value="order.createBy" />
          <van-cell title="创建时间" :value="formatTime(order.createTime)" />
          <van-cell title="最后更新人" :value="order.updateBy" />
          <van-cell title="最后更新时间" :value="formatTime(order.updateTime)" />
        </van-cell-group>
        
        <van-divider>订单明细</van-divider>
        
        <van-cell-group>
          <van-cell
            v-for="(item, index) in order.items"
            :key="index"
            :title="item.productName"
            :label="`数量: ${item.quantity} | 单价: ¥${item.unitPrice}`"
            :value="`¥${item.quantity * item.unitPrice}`"
          />
        </van-cell-group>
        
        <div class="action-buttons">
          <template v-if="!isEditing">
            <!-- 始终显示审批/拒绝按钮，实际权限由后端控制 -->
            <van-button
              type="primary"
              size="large"
              @click="approveOrder"
            >
              批准
            </van-button>
            <van-button
              type="danger"
              size="large"
              @click="rejectOrder"
            >
              拒绝
            </van-button>
            <van-button
              type="default"
              size="large"
              @click="startEditing"
            >
              编辑
            </van-button>
          </template>
          
          <template v-else>
            <van-button
              type="success"
              size="large"
              native-type="submit"
            >
              保存
            </van-button>
            <van-button
              type="default"
              size="large"
              @click="cancelEditing"
            >
              取消
            </van-button>
          </template>
        </div>
      </van-form>
      
      <!-- 日期选择器 -->
      <van-popup v-model:show="showDatePicker" position="bottom">
        <van-date-picker
          @confirm="onDateConfirm"
          @cancel="showDatePicker = false"
        />
      </van-popup>
    </template>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  getPurchaseOrderDetail, 
  approvePurchaseOrder, 
  rejectPurchaseOrder,
  updatePurchaseOrder 
} from '@/api/purchaseOrder'
import { showSuccessToast, showFailToast, showConfirmDialog } from 'vant'

export default {
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    const route = useRoute()
    const router = useRouter()
    const order = ref({ items: [] })
    const editableOrder = ref({})
    const loading = ref(true)
    const isEditing = ref(false)
    const showDatePicker = ref(false)
    
    const statusTagType = computed(() => {
      switch (order.value.status) {
        case 'approved': return 'success'
        case 'rejected': return 'danger'
        default: return 'primary'
      }
    })
    
    const formatTime = (timestamp) => {
      if (!timestamp) return '-'
      return new Date(timestamp).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    const fetchOrderDetail = async () => {
      try {
        loading.value = true
        const { data } = await getPurchaseOrderDetail(props.id)
        order.value = data
        editableOrder.value = { ...data }
      } catch (error) {
        console.error('获取订单详情失败:', error)
        showFailToast('获取订单详情失败')
      } finally {
        loading.value = false
      }
    }
    
    const startEditing = () => {
      isEditing.value = true
    }
    
    const cancelEditing = async () => {
      try {
        await showConfirmDialog({
          title: '确认',
          message: '确定要放弃已修改的内容吗？'
        })
        editableOrder.value = { ...order.value }
        isEditing.value = false
      } catch {
        // 用户点击了取消，不做任何操作
      }
    }
    
    const saveChanges = async () => {
      try {
        loading.value = true
        await updatePurchaseOrder(props.id, editableOrder.value)
        showSuccessToast('订单更新成功')
        isEditing.value = false
        fetchOrderDetail()
      } catch (error) {
        console.error('更新失败:', error)
        showFailToast('更新失败')
      } finally {
        loading.value = false
      }
    }
    
    const approveOrder = async () => {
      try {
        await showConfirmDialog({
          title: '确认',
          message: '确定要批准此采购订单吗？'
        })
        await approvePurchaseOrder(props.id)
        showSuccessToast('订单已批准')
        fetchOrderDetail()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批准订单失败:', error)
          showFailToast(error.response?.data?.message || '批准失败')
        }
      }
    }
    
    const rejectOrder = async () => {
      try {
        await showConfirmDialog({
          title: '确认',
          message: '确定要拒绝此采购订单吗？'
        })
        await rejectPurchaseOrder(props.id)
        showSuccessToast('订单已拒绝')
        fetchOrderDetail()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('拒绝订单失败:', error)
          showFailToast(error.response?.data?.message || '拒绝失败')
        }
      }
    }
    
    const onDateConfirm = (date) => {
      editableOrder.value.orderDate = `${date.selectedValues[0]}-${date.selectedValues[1]}-${date.selectedValues[2]}`
      showDatePicker.value = false
    }
    
    onMounted(() => {
      fetchOrderDetail()
    })
    
    return {
      order,
      editableOrder,
      loading,
      isEditing,
      showDatePicker,
      statusTagType,
      formatTime,
      startEditing,
      cancelEditing,
      saveChanges,
      approveOrder,
      rejectOrder,
      onDateConfirm
    }
  }
}
</script>

<style scoped>
.purchase-order-detail {
  padding-bottom: 60px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin: 16px;
}

.action-buttons .van-button {
  flex: 1;
}
</style>